package practice;

/**
 * @author : DuJiabao
 * @Date : 2021/1/21 17:31
 * @Project : java_learning
 * @File : null.java
 * @Desc :
 */
public class StringPractice {
    public static void main(String[] args) {
        System.out.println(trim_("hfe   "));
//        System.out.println(" ".substring(1, 1));
        System.out.println(reverseSubString("abcdefg", 0, 2));
    }

    /**
     * 将一个字符串进行反转。将字符串中指定部分进行反转。比如“abcdefg”反转为”abfedcg”
     * 左闭右开
     *
     * @param string
     * @param start
     * @param end
     * @return
     */
    public static String reverseSubString(String string, int start, int end) {
        if (start > end) {
            throw new RuntimeException();
        }
        char[] chars = string.toCharArray();
        end -= 1;
        while (start < end) {
            char temp = chars[end];
            chars[end] = chars[start];
            chars[start] = temp;
            start++;
            end--;
        }
        return new String(chars);
    }

    /**
     * 模拟一个trim方法，去除字符串两端的空格。
     *
     * @param string
     * @return
     */
    public static String trim_(String string) {
        if (string != null) {
            int start = 0;
            int end = string.length() - 1;
            while (start <= end && string.charAt(start) == ' ') {
                start++;
            }
            while (start <= end && string.charAt(end) == ' ') {
                end--;
            }
            return string.substring(start, end + 1);
        }
        return null;
    }
}
